package com.bijiawang.user.controller;


import com.bijiawang.user.bean.History;
import com.bijiawang.user.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


@Controller
public class HistoryController {

    @Autowired
    HistoryService historyService;

    @GetMapping("/tohistory/{pageNum}")               //2222点击按钮之后就实现分页   从数据库获取的
    public String sele(Model model, @PathVariable("pageNum") int pageNum, @AuthenticationPrincipal UserDetails userDetails ){
        int lines = 10;
        ArrayList<History> list = historyService.sele(userDetails.getUsername());
        List<History> xmArrayList = null;
        int count = 0;
        if (list.size() != 0) {
             count = list.size() % lines == 0 ? list.size() / lines : list.size() / lines + 1; //页数
            if (pageNum == count) {
                xmArrayList = list.subList(lines * (pageNum - 1), list.size());
            } else {
                xmArrayList = list.subList(lines * (pageNum - 1), lines * pageNum);
            }
        }
        model.addAttribute("emps",xmArrayList);
        model.addAttribute("pagenum",pageNum);
        model.addAttribute("count",count);
        model.addAttribute("username",userDetails.getUsername());
        return "history";
    }

    //，  获取时间--存放在数据库
    @PostMapping("/sethistory")
    public void bb(@RequestParam("username") String username,@RequestParam("url") String url,@RequestParam("goodsname") String goodsname){
        Integer num = historyService.seleUrl(url,username);
        if (num==0){                      //这个判断存在就修改时间，不存在就添加
            History xm = new History();
            ArrayList<History> list = historyService.sele(username);
            xm.setId(list.size()+1);
            xm.setUsername(username);
            xm.setGoodsname(goodsname);
            xm.setUrl(url);
            xm.setDtime(Calendar.getInstance().getTime()); //参数为data类型
            historyService.inster(xm);
        }else{
            historyService.updateDtime(url,username,Calendar.getInstance().getTime());
        }
    }
}
